package com.cooper.android.comm;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.cooper.scraper.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class FolderSelectPreference extends DialogPreference {

	private List<String> items = null;
	private List<String> paths = null;
	private String rootPath;
	private String curPath;
	private TextView mPath;
	private ListView folderList;

	public FolderSelectPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			rootPath = Environment.getExternalStorageDirectory().toString();
			curPath = rootPath;
		} else {
			rootPath = "/";
			curPath = "/";
		}
	}

	@Override
	protected View onCreateView(ViewGroup parent) {
		curPath = getPreferenceManager().getSharedPreferences().getString(
				getKey(), "");
		if ("".equals(curPath)) {
			curPath = rootPath;
		}
		this.setSummary(curPath);

		return super.onCreateView(parent);
	}

	@Override
	protected void onBindDialogView(View view) {
		super.onBindDialogView(view);
		mPath = (TextView) view.findViewById(R.id.local_path);
		folderList = (ListView) view.findViewById(R.id.folder_list);
		folderList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				File file = new File(paths.get(position));
				if (file.isDirectory()) {
					curPath = paths.get(position);
					getFileDir(paths.get(position));
				} else {
					// can open file ..
				}
			}
		});
		getFileDir(curPath);
	}

	private void getFileDir(String filePath) {
		mPath.setText(filePath);
		items = new ArrayList<String>();
		paths = new ArrayList<String>();
		File f = new File(filePath);
		File[] files = f.listFiles();
		if (!filePath.equals(rootPath)) {
			items.add("b1");
			paths.add(rootPath);
			items.add("b2");
			paths.add(f.getParent());
		}
		if (files != null)
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				// only show directory ?
				if (file.isDirectory()) {
					items.add(file.getName());
					paths.add(file.getPath());
				}
			}

		folderList.setAdapter(new FolderAdapter(getContext(), items, paths));
	}

	@Override
	protected void onDialogClosed(boolean positiveResult) {
		if (positiveResult) {
			SharedPreferences.Editor editor = getEditor();
			editor.putString(getKey(), curPath);
			editor.commit();
			this.setSummary(curPath);
		}
	}

}
